package com.example.hrandroidapp.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lib.jason.requestresponsetask.HTTPUtils;
import lib.jason.requestresponsetask.JSONHTTPPoster;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.example.hrandroidapp.LeaveMailDetailActivity;
import com.example.hrandroidapp.R;
import com.example.hrandroidapp.adapter.LeaveApprovalAdapter;
import com.example.hrandroidapp.common.Constant;
import com.example.hrandroidapp.common.HRLog;
import com.example.hrandroidapp.components.ActionsLinearLayout;
import com.example.hrandroidapp.domain.LeavePO;
import com.example.hrandroidapp.domain.UpdatedLeavePO;
import com.example.hrandroidapp.preferences.CurrentServerPreference;
import com.example.hrandroidapp.preferences.UserPreference;
import com.google.gson.Gson;

public class LeavePendingFragment extends Fragment implements LeaveApprovalAdapter.AcceptCallBack {

	private ListView lstLeaveAproval;
	private SwipeRefreshLayout swipeLayout;
	private LeavePendingFragment fragment=this;
	private List<LeavePO> lstLeaves;
	private static TranslateAnimation anim;

	private LeaveApprovalAdapter leaveApprovAdpt;
	private static ActionsLinearLayout actionBar;
	
	private String url=null;
	private String lastLeaveId = "0";
	private boolean myLeave = false;
	
	private final int OPT_APPROVE = 1;
	private final int OPT_REJECT = 2;
	private final String LEAVE_PENDING_STATUS = "1";
	
	private final int PARAM_PENDING = 1;
	private final int PARAM_APPROVE = 2;
	private final int PARAM_REJECT = 3;
	
	private final boolean LEAVE_APPROVE = true;
	
	@Override
	public void onResume() {
		super.onResume();
		loadLeaves();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_leave_pending, container, false);
		
		loadViews(rootView);
		
		actionBar.addActionItem(new ActionsLinearLayout.ActionItem(null, getString(R.string.btn_approve), true,
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        selectChoiceType(OPT_APPROVE);
                    }
                }));
        actionBar.addActionItem(new ActionsLinearLayout.ActionItem(null, getString(R.string.btn_reject), true,
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        selectChoiceType(OPT_REJECT);
                    }
                }));
        actionBar.drawActionBar();
		
	    swipeLayout.setOnRefreshListener(new OnRefresh());
	    swipeLayout.setColorScheme(android.R.color.holo_blue_bright, 
	            android.R.color.holo_green_light, 
	            android.R.color.holo_orange_light, 
	            android.R.color.holo_red_light);
		
	    loadLeaves();
	    
	    lstLeaveAproval.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				LeavePO leavePO = lstLeaves.get(position); 
				Intent intent = new Intent(fragment.getActivity().getApplicationContext(), LeaveMailDetailActivity.class);
				intent.putExtra("leave", leavePO);
				intent.putExtra("pending", "1");
				getActivity().startActivity(intent); 
			}
		});
	    
		return rootView;
	}
	
	private void loadViews(View rootView) {
		lstLeaveAproval = (ListView) rootView.findViewById(R.id.list);
		lstLeaves = new ArrayList<LeavePO>();
		actionBar = (ActionsLinearLayout) rootView.findViewById(R.id.viewGroup_actionBar);
		swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
	}

	private void approveRejectLeavesAPI(List<UpdatedLeavePO> lstUpdatedLeaves, boolean status) {
		url = getResources().getString(R.string.leave_approve_url);
		String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(getActivity()).getSvrIP() + ":" + Constant.PORT + url;
		
		String updateLeaveArr = new Gson().toJson(lstUpdatedLeaves);
		
		HRLog.postLogInfo("leave approve/reject complete( " + status + "): " + completeUrl, "LeavePendingFragment.loadLeaves");
		
		new HTTPUtils(getActivity(), JSONHTTPPoster.MEDIA_JSON_TYPE, completeUrl, 
				populateRequestParameterMap(status, updateLeaveArr), new HTTPUtils.SimpleRequestResponseTaskInterface() {
					
					@Override
					public void handleResponse(String response, int status) throws Exception {
						if(status == 200) {
							Toast.makeText(getActivity(), "Leave process successful...", Toast.LENGTH_LONG);
						}else {
							Toast.makeText(getActivity(), "Fail to process leave process!!!", Toast.LENGTH_LONG);
						}
					}
				}).execute();
	}
	
	private void loadLeaves() {
		if(isAdded()) {
			url = getResources().getString(R.string.leave_url);
			String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(getActivity()).getSvrIP() + ":" + Constant.PORT + url;
			
			HRLog.postLogInfo("leave pending url complete: " + completeUrl, "LeavePendingFragment.loadLeaves"); 
			
			new HTTPUtils(getActivity(), JSONHTTPPoster.MEDIA_FORM_URLENCODED, completeUrl, populateRequestParameterString(), 
					new HTTPUtils.SimpleRequestResponseTaskInterface() {
	
				@Override
				public void handleResponse(String responseStr, int status) throws Exception {
					JSONArray jsonArray = new JSONArray(responseStr);
					lstLeaves.clear();
					for (int i = 0; i < jsonArray.length(); i++) {
	
		                JSONObject jsonobject = jsonArray.getJSONObject(i);
		                LeavePO leavePO = new LeavePO();
		                
		                leavePO.setColor(jsonobject.getString("color"));
		                String createdDate = jsonobject.getString("createdDate");
		                
		                leavePO.setCreatedDate(createdDate); 
		                
		                leavePO.setEmployeeName(jsonobject.getString("employeeName"));
		                
		                createdDate = jsonobject.getString("endDateTime");
		                leavePO.setEndDateTime(createdDate); 
		                leavePO.setLeaveDescription(jsonobject.getString("leaveDescription"));
		                leavePO.setLeaveId(Long.parseLong(jsonobject.getString("leaveId")));
		                
		                createdDate = jsonobject.getString("startDateTime");
		                leavePO.setStartDateTime(createdDate); 
		                leavePO.setReason(jsonobject.getString("subject"));
		                leavePO.setTotalDays(Double.parseDouble(jsonobject.getString("totalDays")));
		                lstLeaves.add(leavePO); 
		           }
					
					Collections.sort(lstLeaves, new Comparator<LeavePO>() {
	
						@Override
						public int compare(LeavePO obj1, LeavePO obj2) {
							return obj2.getCreatedDate().compareTo(obj1.getCreatedDate());
						}
					});
					
					leaveApprovAdpt = new LeaveApprovalAdapter(fragment.getActivity().getApplicationContext(), lstLeaves, fragment);
				    lstLeaveAproval.setAdapter(leaveApprovAdpt);
				    
					
					HRLog.postLogDebug("JSON string: " + responseStr, "LeavePendingFragment.onCreateView");
	
				}
				
			}).execute();
		}
	}
	
	public static void showApproveButton() {
		int translationY = 0;
		if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
			anim = new TranslateAnimation(0, 0, translationY, translationY);
			anim.setFillAfter(true);
			anim.setDuration(0);
			actionBar.startAnimation(anim);
		} else {
			actionBar.setTranslationY(translationY);
		}
	}

	private class OnRefresh implements OnRefreshListener {

		@Override
		public void onRefresh() {
			new Handler().postDelayed(new Runnable() {
		        @Override public void run() {
		            swipeLayout.setRefreshing(false);
		        }
		    }, 5000);
		}
		
	}

	@Override
	public void setAccptVisible(boolean flag) {
		if(flag){
			actionBar.setVisibility(View.GONE); 
		}else {
			actionBar.setVisibility(View.VISIBLE); 
		}
	}
	
	private enum ChoiceType {
        APPROVE, REJECT
    }
	
	private void selectChoiceType(int option) {
		List<UpdatedLeavePO> applyLstLeaves = new ArrayList<UpdatedLeavePO>();
		if(option == 1) {			// approve
			List<LeavePO> lstLeaves = leaveApprovAdpt.getAllItems();
			List<LeavePO> newLstLeaves = new ArrayList<LeavePO>();
			
			actionBar.setVisibility(View.GONE);
			for(int i=0; i<lstLeaves.size(); i++) {
				if(!lstLeaves.get(i).isCheck()) {
					newLstLeaves.add(lstLeaves.get(i));
				}else {
					// send check mails to api
					UpdatedLeavePO updatedLeavePO = new UpdatedLeavePO(actionBar.getLeaveCommment(), lstLeaves.get(i).getLeaveId());
					 applyLstLeaves.add(updatedLeavePO);
				}
			}
			
			approveRejectLeavesAPI(applyLstLeaves, LEAVE_APPROVE);
			leaveApprovAdpt = new LeaveApprovalAdapter(getActivity().getApplicationContext(), newLstLeaves, fragment);
		    lstLeaveAproval.setAdapter(leaveApprovAdpt);
		}else if(option == 2) {			// reject
			List<LeavePO> lstLeaves = leaveApprovAdpt.getAllItems();
			List<LeavePO> newLstLeaves = new ArrayList<LeavePO>();
			
			actionBar.setVisibility(View.GONE);
			for(int i=0; i<lstLeaves.size(); i++) {
				if(!lstLeaves.get(i).isCheck()) {
					newLstLeaves.add(lstLeaves.get(i));
				}else {
					// send check mails to api
					UpdatedLeavePO updatedLeavePO = new UpdatedLeavePO(actionBar.getLeaveCommment(), lstLeaves.get(i).getLeaveId());
					applyLstLeaves.add(updatedLeavePO); 
				}
			}
			
			approveRejectLeavesAPI(applyLstLeaves, !LEAVE_APPROVE);
			leaveApprovAdpt = new LeaveApprovalAdapter(getActivity().getApplicationContext(), newLstLeaves, fragment);
		    lstLeaveAproval.setAdapter(leaveApprovAdpt);
		}
	}
	
	private String populateRequestParameterMap(boolean approve, String updatedLeaveLst) {
		JSONObject approvedData = new JSONObject();
		try {
			approvedData.put("approved", approve);
			approvedData.put("dataList", new JSONArray(updatedLeaveLst)); 
			approvedData.put("loginId", UserPreference.getLoginId(getActivity()));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return approvedData.toString();
	}

	public Map<String, String> populateRequestParameterString() {
		Map<String, String> l_maps = new HashMap<String, String>();
		l_maps.put("leaveStatus", LEAVE_PENDING_STATUS);
		l_maps.put("leaveId", lastLeaveId);
		l_maps.put("loginId", UserPreference.getLoginId(getActivity()));
		l_maps.put("size", String.valueOf(Constant.LEAVE_SIZE));
		l_maps.put("myLeave", String.valueOf(myLeave));
		return l_maps;
	}
	
	
}
